from model.ctc_model import model_all,conv_shape
import numpy as np
from keras import backend as K
import os

model_path = "model/fpyzm_ctc_weights.h5"
test_path = r"datasets\test"
train_path = r"datasets\train"


def evaluate():
    test_x = np.load(os.path.join(test_path,"inputs.npy"))
    test_y_str = np.load(os.path.join(test_path,"labels_str.npy"))
    test_y_color = np.load(os.path.join(test_path,"labels_color.npy"))
    model_all.load_weights(model_path)
    y_pred = model_all.predict(test_x,batch_size=32)
    print(len(y_pred),y_pred[0].shape)
    pred_str = K.get_value(K.ctc_decode(y_pred[0], input_length=np.ones(len(test_x), dtype=int) * int(conv_shape[1]), )[0][0])[:,:6]
    pred_color = K.get_value(K.ctc_decode(y_pred[1], input_length=np.ones(len(test_x), dtype=int) * int(conv_shape[1]), )[0][0])[:,:6]
    get_acc(pred_str,test_y_str,"string")
    get_acc(pred_color,test_y_color,"color")


def search_table(table,idx):
    idx = int(idx)
    if idx < 0:
        return "-null"
    elif idx >= len(table):
        return "null"
    else:
        return table[idx]


def get_acc(Y, Y_,typ="string"):

    with open(typ+".txt","r",encoding="utf-8") as f:
        text = f.read()
    acc = 0
    for y, y_ in zip(Y, Y_):
        if len(y) != 6:
            print(y)
            continue
        cmp = (y_ == y)
        if False not in cmp:
            acc += 1
        else:
            pred = [search_table(text, item) for item in y]
            real = [search_table(text, item) for item in y_]
            print(pred, real)

    ratio = acc / len(Y_)
    if typ == "string":
        print('字符识别率:%f' % ratio)
    else:
        print('颜色识别率:%f' % ratio)


if __name__ == "__main__":
    evaluate()

